﻿using DB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace OMSBlackTechnology.Controllers
{
    public class PriceListController : Controller
    {
        // GET: PriceList
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(object obj)
        {

            


            Stopwatch sw = new Stopwatch();
            sw.Start();

            /*
            using (nopdbEntities ent = new nopdbEntities())
            {
                var productList = (from p in ent.Product where !p.Deleted select p).ToList();

                foreach (var product in productList)
                {
                    var prcieLists = (from pl in ent.PriceList where pl.ProductId == product.Id && pl.Spu == product.Sku orderby pl.Id descending select pl).ToList();
                    if (prcieLists != null && prcieLists.Count() > 0)
                    {
                        var list_distinct = prcieLists.GroupBy(g => new { g.VendorId, g.WarehouseId }).Select(s => s.FirstOrDefault()).ToList();

                        foreach (var dist in list_distinct)
                        {
                            var combs = (from f in ent.ProductAttributeCombination where f.ProductId == product.Id select f).ToList();
                            var isFirst = true;

                            var availableFrist = prcieLists.Where(p => p.VendorId == dist.VendorId && p.WarehouseId == dist.WarehouseId).FirstOrDefault();                      

                            if (availableFrist != null)
                            {
                                var addList = new List<PriceList>();
                                foreach (var comb in combs)
                                {
                                    var internationalCodeAndSize = comb.Sku;
                                    var internationalCode = string.Empty;
                                    var size = string.Empty;

                                    if (!string.IsNullOrWhiteSpace(internationalCodeAndSize) && internationalCodeAndSize.Contains("|"))
                                    {
                                        var codeSize = internationalCodeAndSize.Split('|');
                                        internationalCode = codeSize[0];
                                        size = codeSize[1];
                                    }

                                    if (isFirst)
                                    {
                                        availableFrist.InternationalCode = internationalCode;
                                        availableFrist.Size = size;
                                        availableFrist.Sku = comb.Sku;
                                        isFirst = false;
                                    }
                                    else
                                    {
                                        var entity = new PriceList();
                                        entity.Applicant = availableFrist.Applicant;
                                        entity.AvailableTime = availableFrist.AvailableTime;
                                        entity.CheckStatus = availableFrist.CheckStatus;
                                        entity.CreateTime = DateTime.Now;
                                        entity.Currency = availableFrist.Currency;
                                        entity.DiscountRate = availableFrist.DiscountRate;
                                        entity.InternationalCode = internationalCode;
                                        entity.IsAvailable = availableFrist.IsAvailable;
                                        entity.IsInSelling = availableFrist.IsInSelling;
                                        entity.IsWaitChange = availableFrist.IsWaitChange;
                                        entity.Note = "供应商主动调价，审核通过";
                                        entity.Operator = "系统";
                                        entity.PrepareAvailableTime = availableFrist.PrepareAvailableTime;
                                        entity.Price = availableFrist.Price;
                                        entity.Priced = availableFrist.Priced;
                                        entity.ProductId = availableFrist.ProductId;
                                        entity.ProductName = availableFrist.ProductName;
                                        entity.Size = size;
                                        entity.Sku = comb.Sku;
                                        entity.Spu = availableFrist.Spu;
                                        entity.TaxRebateRate = availableFrist.TaxRebateRate;
                                        entity.VendorId = availableFrist.VendorId;
                                        entity.WarehouseId = availableFrist.WarehouseId;
                                        addList.Add(entity);
                                    }
                                }
                                ent.PriceList.AddRange(addList);
                                ent.SaveChanges();
                                continue;
                            }
                        }
                    }
                }

            }
            */

            using (nopdbEntities ent = new nopdbEntities())
            {
                var queryList = (
                    from f in ent.PriceList
                    join p in ent.Product on f.ProductId equals p.Id
                    where !p.Deleted  //商品未删除
                    orderby f.Id descending
                    select f
                    ).ToList();

                var addList = new List<PriceList>();

                var updateList = new List<PriceList>();

                var groupList = queryList.GroupBy(g => new { g.VendorId, g.WarehouseId, g.ProductId }).Select(s => s.FirstOrDefault()).ToList();

                var availableProductIds = queryList.Select(p => p.ProductId).Distinct().ToList();

                var queryCombs = (from f in ent.ProductAttributeCombination where availableProductIds.Contains(f.ProductId) select f).ToList();
            
                foreach (var available in groupList)
                {
                    var combs = queryCombs.Where(p => p.ProductId == available.ProductId).ToList();

                    var isFirst = true;

                    foreach (var comb in combs)
                    {
                        var internationalCodeAndSize = comb.Sku;
                        var internationalCode = string.Empty;
                        var size = string.Empty;

                        if (!string.IsNullOrWhiteSpace(internationalCodeAndSize) && internationalCodeAndSize.Contains("|"))
                        {
                            var codeSize = internationalCodeAndSize.Split('|');
                            internationalCode = codeSize[0];
                            size = codeSize[1];
                        }

                        if (string.IsNullOrWhiteSpace(internationalCode) || string.IsNullOrWhiteSpace(size))
                        {
                            continue;
                        }

                        if (isFirst)
                        {
                            available.InternationalCode = internationalCode;
                            available.Size = size;
                            available.Sku = comb.Sku;
                            available.Note = "供应商主动调价，审核通过";
                            available.IsAvailable = true;
                            updateList.Add(available);
                            isFirst = false;
                        }
                        else
                        {
                            var entity = new PriceList();
                            entity.Applicant = available.Applicant;
                            entity.AvailableTime = available.AvailableTime;
                            entity.CheckStatus = available.CheckStatus;
                            entity.CreateTime = DateTime.Now;
                            entity.Currency = available.Currency;
                            entity.DiscountRate = available.DiscountRate;
                            entity.InternationalCode = internationalCode;
                            entity.IsAvailable = available.IsAvailable;
                            entity.IsInSelling = available.IsInSelling;
                            entity.IsWaitChange = available.IsWaitChange;
                            entity.Note = "供应商主动调价，审核通过";
                            entity.Operator = "系统";
                            entity.PrepareAvailableTime = available.PrepareAvailableTime;
                            entity.Price = available.Price;
                            entity.Priced = available.Priced;
                            entity.ProductId = available.ProductId;
                            entity.ProductName = available.ProductName;
                            entity.Size = size;
                            entity.Sku = comb.Sku;
                            entity.Spu = available.Spu;
                            entity.TaxRebateRate = available.TaxRebateRate;
                            entity.VendorId = available.VendorId;
                            entity.WarehouseId = available.WarehouseId;
                            addList.Add(entity);
                        }
                    }

                }

                ent.BulkUpdate(updateList);
                ent.BulkInsert(addList);
                ent.BulkSaveChanges();
            }

            sw.Stop();
            TimeSpan ts = sw.Elapsed;
            TempData["Message"] = "耗时" + ts.TotalMinutes.ToString() + "分钟";

            RedirectToAction("Index");
            return View();
        }
    }
}

public class Prices
{
    public int Currency { get; set; }
    public int? ProductId { get; set; }
    public string Spu { get; set; }
    public int? VendorId { get; set; }
    public int? WarehouseId { get; set; }
}